<template>
  <div class="note-detail">
    <!-- 作者信息区 -->
    <div class="userinfo-wrapper">
      <van-nav-bar
        :fixed="true"
        :safe-area-inset-top="true"
        :placeholder="true"
      >
        <template #left>
          <van-icon name="arrow-left" @click="routerBack" size="18" />
          <div class="infoBox" @click="routerTo(`/user/${userinfo._id}`)">
            <img class="small-img" :src="userinfo.headImg" alt="" />
            <div class="name">{{ userinfo.username }}</div>
          </div>
        </template>
        <template #right>
          <div class="btn" v-if="!isMe">
            <div class="hasFocusd" @click="doUnFocus" v-if="isfocusd">
              已关注
            </div>
            <button class="focus" @click="doFocus" v-else>+ 关注</button>
          </div>
          <!-- <van-icon name="ellipsis" @click="show = true" size="18" /> -->
        </template>
      </van-nav-bar>
    </div>
    <!-- 轮播图 -->
    <van-swipe class="swipe-wrapper" v-if="note.imgList.length !== 0">
      <van-swipe-item v-for="(item, index) in note.imgList" :key="item._id">
        <van-image
          @click="doPreview(index)"
          width="100%"
          height="100%"
          fit="contain"
          :src="item"
        >
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
        </van-image>
      </van-swipe-item>
      <template #indicator="{ active, total }">
        <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
      </template>
    </van-swipe>
    <!-- 主内容区 -->
    <div class="content-wrapper">
      <div class="title">
        <div class="text">
          <strong>{{ note.title }}</strong>
        </div>
        <div class="logo"></div>
      </div>
      <div class="tag-wrapper">
        <div class="placeTag">
          <div class="logo"><img src="@/assets/img/locate.png" alt="" /></div>
          <div class="placeName">{{ note.place }}</div>
        </div>
      </div>
      <div class="content">
        {{ note.content }}
      </div>
      <div class="createTime">发布于 &nbsp;{{ note.createTime }}</div>
    </div>
    <van-divider />
    <!-- 预展评论区 -->
    <CommentsWrapper :comments="note.comments" v-if="SW" />
    <!-- 选择区 -->
    <van-grid
      column-num="3"
      direction="horizontal"
      icon-size="24px"
      :border="false"
    >
      <van-grid-item @click="showShare = true" icon="share-o" text="" />
      <van-grid-item v-if="!isLiker" @click="onlike()" icon="like-o" text="" />
      <van-grid-item v-else @click="onunlike" icon="like" text="" />
      <van-grid-item
        v-if="SW"
        @click="allCommentsAction = true"
        icon="chat-o"
        :text="`${note.comments.length}`"
      />
    </van-grid>
    <!-- 全部评论弹出框 -->
    <van-action-sheet v-model:show="allCommentsAction" title="全部评论">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        @load="onCommentListLoad"
      >
        <van-cell v-for="item in note.comments" :key="item._id">
          <template #title>
            <LeaverInfo :leaver="item.leaver" />
          </template>
          <div class="wrods-wrapper">
            {{ item.words }}
          </div>
          <div class="time">
            {{ item.time }}
          </div>
        </van-cell>
      </van-list>
      <van-cell-group inset>
        <van-field
          v-model="leaveWords"
          rows="1"
          autosize
          :maxlength="200"
          type="textarea"
          placeholder="请输入留言"
        >
          <template #button>
            <van-button
              size="small"
              color="#0096aa"
              type="primary"
              @click="releaseLeaveWords"
              >发布</van-button
            >
          </template></van-field
        >
      </van-cell-group>
    </van-action-sheet>
    <!-- 分享面板弹出框 -->
    <van-share-sheet
      v-model:show="showShare"
      title="立即分享给好友"
      :options="options"
      @select="onShareSelect"
    />
  </div>
</template>
<script>
import { reactive, toRefs } from '@vue/reactivity';
import { onBeforeMount } from '@vue/runtime-core';
import { useRoute, useRouter } from 'vue-router';
import LeaverInfo from './components/LeaverInfo.vue';
import { leaveWords, doLike, doUnLike } from '@/api/interface';
import { getNoteById, addFollower, cancelFollower } from '@/api/interface';
import CommentsWrapper from './components/Comments-Wrapper.vue';
import { useStore } from 'vuex';
import { Toast, Dialog, ImagePreview } from 'vant';

export default {
  components: { CommentsWrapper, LeaverInfo },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const state = reactive({
      // 展示分享面板
      showShare: false,
      // 展示评论面板
      allCommentsAction: false,
      // van-list是否触发加载图标
      loading: false,
      // van-list是否加载完毕
      finished: true,
      // 分享面板选项
      options: [
        { name: '微信', icon: 'wechat' },
        { name: '微博', icon: 'weibo' },
        { name: '复制链接', icon: 'link' },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' },
      ],
      // ***********************优化************************************预留做全部评论懒加载的字段，后面全部评论用该字段代替note.comments做v-for循环
      list: [
        {
          createBy: '',
        },
      ],
      // 这篇文章的作者
      userinfo: {},
      // 这篇文章
      note: {
        imgList: [],
      },
      // 双向绑定的留言输入框内容
      leaveWords: '',
      // 是否以及是我的关注了
      isfocusd: false,
      isLiker: false,
      isMe: true,
      isCollect: false,
      SW: false,
    });

    const routerTo = (url) => {
      router.push({
        path: url,
      });
    };
    const routerBack = () => {
      router.go(-1);
    };
    const releaseLeaveWords = async () => {
      if (state.leaveWords.length == 0) {
        Toast('评论要写喔~');
        return;
      }
      let reg = new RegExp('/', 'g');
      let day = new Date()
        .toLocaleDateString()
        .replace(reg, '-')
        .concat(` ${new Date().getHours()}:${new Date().getMinutes()}`); //2022-4-28 9:58
      await leaveWords({
        id: route.params.id,
        comments: {
          words: state.leaveWords,
          leaver: store.state.userinfo._id,
          time: day,
        },
      })
        .then((res) => {
          if (res.success) {
            window.location.href = `/note/detail/${route.params.id}`;
          }
        })
        .catch((err) => {
          console.log('留言出问题了', err);
        });
    };

    const onShareSelect = (option) => {
      Toast(option.name);
      state.showShare = false;
    };
    const onlike = async () => {
      await doLike({
        id: route.params.id,
        liker: store.state.userinfo._id,
      }).then(() => {
        state.isLiker = true;
      });
    };
    const onunlike = async () => {
      state.isLiker = false;
      await doUnLike({
        id: route.params.id,
        liker: store.state.userinfo._id,
      }).then((res) => {
        if (res.success) {
          state.isLiker = false;
        }
      });
    };
    const onCommentListLoad = () => {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          state.list.value.push(state.list.value.length + 1);
        }
        // 加载状态结束
        state.loading.value = false;
        // 数据全部加载完成
        if (state.list.value.length >= 40) {
          state.finished.value = true;
        }
      }, 1000);
    };
    // 图片预览
    const doPreview = (index) => {
      ImagePreview({
        images: state.note.imgList,
        closeable: true,
        startPosition: index,
      });
    };
    const doFocus = async () => {
      Toast('关注成功！');
      await addFollower({ followerId: state.userinfo._id })
        .then((res) => {
          if (res.status == '200') {
            state.isfocusd = true;
          }
        })
        .catch((err) => {
          console.log('关注的的时候出错啦', err);
        });
    };
    const doUnFocus = async () => {
      Dialog.confirm({
        title: '提示',
        message: '你确定要取关这个小可爱嘛？',
      })
        .then(async () => {
          // on confirm
          await cancelFollower({ followerId: state.userinfo._id })
            .then((res) => {
              if (res.status == '200') {
                state.isfocusd = false;
              }
            })
            .catch((err) => {
              console.log('点赞的时候出错啦', err);
            });
        })
        .catch(() => {
          // on cancel
        });
    };

    const isIndexOf = (arr, item) => {
      if (arr.indexOf(item) !== -1) {
        // 已经关注了
        return true;
      }
      return false;
    };

    onBeforeMount(async () => {
      // 获取登录者的用户数据
      await store.dispatch('_getUserInfo');
      // 获取点击对应的笔记数据
      await getNoteById({ id: route.params.id })
        .then((res) => {
          state.note = res.data;
          state.userinfo = res.data.author;
          state.SW = true;
        })
        .catch((err) => {
          console.log(err);
        });
      state.isfocusd = isIndexOf(state.userinfo.fans, store.state.userinfo._id);
      state.isLiker = isIndexOf(state.note.like, store.state.userinfo._id);

      // 判断这篇文章是不是自己写的
      if (state.note.author._id == store.state.userinfo._id) {
        state.isMe = true;
      } else {
        state.isMe = false;
      }
    });
    return {
      ...toRefs(state),
      routerBack,
      routerTo,
      doFocus,
      doUnFocus,
      doPreview,
      onCommentListLoad,
      releaseLeaveWords,
      onShareSelect,
      onlike,
      onunlike,
    };
  },
};
</script>
<style lang="less" scoped>
.note-detail {
  overflow-x: hidden;
  overflow-y: scroll;
  margin-bottom: 100px;
}

.swipe-wrapper {
  width: 100%;
  height: 45vh;
  .custom-indicator {
    position: absolute;
    right: 5px;
    bottom: 5px;
    padding: 2px 5px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
  }
}

.userinfo-wrapper {
  .focus {
    box-sizing: border-box;
    margin-right: 18px;
    border-radius: 10px;
    border: none;
    background: rgb(85, 205, 221);
    padding: 3px 12px;
    color: #ffffff;
    font-size: 12px;
  }
  .hasFocusd {
    margin-right: 18px;
    background: rgb(175, 176, 176);
    border-radius: 10px;
    box-sizing: border-box;
    font-size: 12px;
    padding: 3px 12px;
    color: rgb(56, 55, 55);
    font-family: '黑体';
  }
  .infoBox {
    margin: 0px 10px;
    display: flex;
    align-items: center;
    .small-img {
      width: 25px;
      height: 25px;
      border-radius: 50px;
    }
    .name {
      padding: 0 10px;
    }
  }
}

.content-wrapper {
  width: 95%;
  margin: 0 auto;
  word-break: break-all;

  .title {
    padding-top: 12px;
    display: flex;
    .text {
      font-size: 20px;
      font-family: '微软雅黑';
      word-spacing: break-all;
    }
    // .logo {
    //   width: 70px;
    // }
  }
  .tag-wrapper {
    margin: 12px 0;
    display: flex;

    .placeTag {
      display: flex;
      align-items: center;
      border-radius: 6px;
      background: #b8eff3;
      white-space: nowrap;
      padding: 4px 7px;
      padding-top: 5px;
      .logo {
        padding-right: 3px;
        img {
          width: 14px;
          height: 14px;
          padding: 0 3px;
        }
      }
      .placeName {
        padding-right: 3px;
        color: #0096aa;
        font-size: 12px;
        font-weight: 600;
        white-space: nowrap;
        line-height: 8px;
      }
    }
  }
  .content {
    color: rgb(95, 92, 92);
    font-size: 14px;
    line-height: 20px;
    font-weight: 600;
    white-space: pre-line;
  }
  .createTime {
    color: rgb(153, 153, 153);
    font-size: 10px;
    font-weight: 700;
    margin-top: 10px;
  }
}
</style>
